﻿using Learun.Util.SqlSugar;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-14 10:58
    /// 描 述：业务表
    /// </summary>
    public class ec_business_tableService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_business_tableEntity> _businessTableRepository => new Repository<ec_business_tableEntity>();
        #endregion
        #region 获取数据

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_business_tableEntity> GetList( string queryJson )
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t.* 
                         FROM ec_business_table t");
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["BusinessTableName"].IsEmpty())
                {
                    dp.Add(new SugarParameter("BusinessTableName", "%" + queryParam["BusinessTableName"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.BusinessTableName LIKE @BusinessTableName ");
                }
                strSql.Append(" ORDER BY t.CreateTime DESC ");
                //return this.BaseRepository().FindList<ec_business_tableEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_business_tableEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取列表分页数据
        /// <param name="pagination">分页参数</param>
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_business_tableEntity> GetPageList(Pagination pagination, string queryJson)
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t.* 
                        FROM ec_business_table t ");
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["BusinessTableName"].IsEmpty())
                {
                    dp.Add(new SugarParameter("BusinessTableName", "%" + queryParam["BusinessTableName"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.BusinessTableName LIKE @BusinessTableName ");
                }
                if (!queryParam["IsCopyData"].IsEmpty())
                {
                    dp.Add(new SugarParameter("IsCopyData", queryParam["IsCopyData"].ToBool(), DbType.Boolean));
                    strSql.Append(" AND t.IsCopyData = @IsCopyData ");
                }
                //return this.BaseRepository().FindList<ec_business_tableEntity>(strSql.ToString(), dp, pagination);
                return SqlSugarHelper.Db.SqlQueryable<ec_business_tableEntity>(strSql.ToString()).AddParameters(dp).ToPageList(pagination.page, pagination.rows);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_business_tableEntity GetEntity(string keyValue)
        {
            try
            {
                //return this.BaseRepository().FindEntity<ec_business_tableEntity>(keyValue);
                return _businessTableRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, List<int> listProjectIndex)
        {
            //var db = this.BaseRepository().BeginTrans();
            _businessTableRepository.AsTenant().BeginTran();
            try
            {
                ec_business_tableEntity entity = GetEntity(keyValue);
                if (listProjectIndex != null && listProjectIndex.Count > 0)
                {
                    //删除时，需要删除各个项目的业务表
                    string sqlStatement = "";
                    foreach (var item in listProjectIndex)
                    {
                        sqlStatement += $" DROP TABLE IF EXISTS `{entity?.BusinessTableCode}_{item}`;";
                    }
                    //db.ExecuteBySql(sqlStatement);
                    SqlSugarHelper.Db.Ado.ExecuteCommand(sqlStatement);
                }
                //db.Delete<ec_business_tableEntity>(t => t.BusinessTableID == keyValue);
                _businessTableRepository.DeleteById(keyValue);
                //db.Commit();
                _businessTableRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                //db.Rollback();
                _businessTableRepository.AsTenant().RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_business_tableEntity entity, List<int> listProjectIndex)
        {
            //var db = this.BaseRepository().BeginTrans();
            _businessTableRepository.AsTenant().BeginTran();
            try
            {
                //新增、编辑业务数据表时，需要判断各项目对应的业务表是否存在，如果不存在就新增。
                if (listProjectIndex != null && listProjectIndex.Count > 0)
                {
                    string sqlStatement = "";
                    foreach (var item in listProjectIndex)
                    {
                        sqlStatement += $" CREATE TABLE IF NOT EXISTS `{entity?.BusinessTableCode}_{item}`(LIKE {entity?.BusinessTableCode});";
                    }
                    //db.ExecuteBySql(sqlStatement);
                    SqlSugarHelper.Db.Ado.ExecuteCommand(sqlStatement);
                }
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    //db.Update(entity);
                    _businessTableRepository.Update(entity);
                }
                else
                {
                    entity.Create();
                    //db.Insert(entity);
                    _businessTableRepository.Insert(entity);
                }
                //db.Commit();
                _businessTableRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                //db.Rollback();
                _businessTableRepository.AsTenant().RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
